/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.bot.server;

import com.sun.net.httpserver.HttpExchange;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map.Entry;
import javax.activation.MimetypesFileTypeMap;
import net.bot.utils.IOUtils;
import net.bot.utils.URLUtils;

/**
 *
 * @author phichidev
 */
public class DefaultRequestHandler implements RequestHandler {

    private String rootPath;

    public DefaultRequestHandler(String rootPath) {
        this.rootPath = rootPath;
    }

    @Override
    public void handleRequest(HttpExchange httpExchange) {
        try {
            this.trace(httpExchange);
            this.sendFileContent(httpExchange);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    protected void trace(HttpExchange httpExchange) throws IOException {
        System.out.println("@Request: " + httpExchange.getRequestURI());
        System.out.println("\tIP: " + httpExchange.getRemoteAddress());
        System.out.println("\tHeaders: ");
        for (Entry<String, List<String>> entry : httpExchange.getRequestHeaders().entrySet()) {
            System.out.println("\t\t" + entry.getKey() + "\t" + entry.getValue());
        }
        System.out.println("\tMethod: " + httpExchange.getRequestMethod());
        System.out.println("\tGet Query: " + URLUtils.getQueryMap(httpExchange.getRequestURI().getQuery()));
        if (httpExchange.getRequestMethod().equalsIgnoreCase("post")) {
            String requestBody = IOUtils.toString(httpExchange.getRequestBody());
            System.out.println("\tPost Query: " + URLUtils.getQueryMap(requestBody));
        }
    }

    protected void sendFileContent(HttpExchange httpExchange) {
        String path = httpExchange.getRequestURI().getPath();
        if (path.equals("/")) {
            path = "/index.htm";
        }
        File file = new File(rootPath + path);
        OutputStream os = httpExchange.getResponseBody();
        if (!file.exists() || file.isDirectory()) {
            try {
                byte[] error = "404 Not Found".getBytes();
                httpExchange.sendResponseHeaders(404, error.length);
                os.write(error);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    os.close();
                } catch (Exception e) {
                }
            }
            return;
        }
        String contentType = new MimetypesFileTypeMap().getContentType(file);
        httpExchange.getResponseHeaders().set("Content-Type", contentType);
        try {
            httpExchange.sendResponseHeaders(200, file.length());
            IOUtils.copy(new FileInputStream(file), os);
        } catch (Exception e) {
        } finally {
            try {
                os.close();
            } catch (Exception e) {
            }
        }
    }
}
